package com.miguo.db;

import android.content.Context;

import com.miguo.app.AppContext;
import com.miguo.bean.CategoryThemeBean;
import com.miguo.db.CategoryThemeDao.Properties;

import java.util.List;

import de.greenrobot.dao.query.QueryBuilder;

public class CategoryThemeDB {
    private static Context mContext;
    private static CategoryThemeDB instance;

    private CategoryThemeDao category_themeDao;

    private CategoryThemeDB() {
    }

    public static CategoryThemeDB getInstance(Context context, boolean ClearSession) {
        if (instance == null) {
            instance = new CategoryThemeDB();
            if (mContext == null) {
                mContext = context;
            }

            // 数据库对象
            DaoSession daoSession = AppContext.getDaoSession(mContext,
                    ClearSession);
            instance.category_themeDao = daoSession.getCategoryThemeDao();
        }
        return instance;
    }

    public List<CategoryThemeBean> loadAll() {
        return category_themeDao.loadAll();
    }

    //position  1 = 主题  2 = 热门主题
    public List<CategoryThemeBean> findTheirId(Long their_id, int position) {
        QueryBuilder<CategoryThemeBean> qb = category_themeDao.queryBuilder();
        qb.where(Properties.Their_id.eq(their_id));
        qb.where(Properties.Position.eq(position));
        qb.orderAsc(Properties.Sort);// 排序依据
        return qb.list();
    }

    /**
     * insert or update noteList use transaction
     *
     * @param list
     */
    public void saveList(final List<CategoryThemeBean> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        category_themeDao.getSession().runInTx(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < list.size(); i++) {
                    CategoryThemeBean note = list.get(i);
                    category_themeDao.insertOrReplace(note);
                }
            }
        });

    }

    /**
     * delete all
     */
    public void deleteAll() {
        category_themeDao.deleteAll();
    }
}